import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jetour_line/base_widget/base_image.dart';
import 'package:jetour_line/base_widget/base_scaffold.dart';
import 'package:jetour_line/base_widget/image_network_widget.dart';
import 'package:jetour_line/base_widget/loading_widget.dart';
import 'package:jetour_line/base_widget/my_refresh_view.dart';
import 'package:jetour_line/my_colors.dart';
import 'package:jetour_line/network/jetour_http.dart';
import 'package:jetour_line/pages/common/commonDetail/common_detail_page.dart';
import 'package:jetour_line/pages/creatTravel/creat_travel_page.dart';
import 'package:jetour_line/utils/extension_int.dart';
import 'package:jetour_line/utils/page_push_utils.dart';

import '../../base_widget/my_alert.dart';
import '../../models/guide_list_model.dart';

class MineCommonPageScreen extends StatefulWidget {
  const MineCommonPageScreen({Key? key}) : super(key: key);

  @override
  State<MineCommonPageScreen> createState() => _MineCommonPageScreenState();
}

class _MineCommonPageScreenState extends State<MineCommonPageScreen> {
  List<ListElement>? list;
  int page = 1;
  final MyRefreshViewController _controller = MyRefreshViewController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getList();
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
        backgroundColor: MyColors.colorF1F1F1,
        title: "我的共创",
        body: (list == null || list!.isEmpty)
            ? LoadingWidget(
                type: (list != null && list!.isEmpty) ? 1 : 0,
              )
            : Padding(
                padding: EdgeInsets.all(20.px),
                child: MyRefreshView(
                  refreshCallBack: (bool isUp) {
                    if (isUp) {
                      page = 1;
                    } else {
                      page++;
                    }
                    getList();
                  },
                  controller: _controller,
                  child: ListView.builder(
                      itemCount: list!.length,
                      itemBuilder: (context, index) {
                        return itemWidget(index);
                      }),
                ),
              ));
  }

  Widget itemWidget(int index) {
    String url = list![index].logo;
    String caption = list![index].caption;
    String? msg;
    String? startCity = list![index].startCity;

    if (startCity != null && startCity.isNotEmpty) {
      msg = startCity;
      String? endCity = list![index].endCity;
      if (endCity != null && endCity.isNotEmpty) {
        msg = '$msg-$endCity';
      }
    }
    if (list![index].totalDay > 0) {
      if (msg == null) {
        int day = list![index].totalDay.toInt();
        msg = '$day天';
      } else {
        msg = '$msg · ${list![index].totalDay.toInt()}天';
      }
    }

    return Padding(
      padding: EdgeInsets.only(
        left: 10.px,
        top: 20.px,
        right: 10.px,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(4.px)),
        child: GestureDetector(
          onTap: () {
            PagePushUtils.push(
                context, CommonDetailScreen(id: list![index].id));
          },
          child: Container(
            color: MyColors.white,
            width: double.infinity,
            height: 258.px,
            child: Padding(
              padding: EdgeInsets.all(
                24.px,
              ),
              child: Row(
                children: [
                  SizedBox(
                    width: 158.px,
                    height: 180.px,
                    child: Stack(
                      children: [
                        Positioned(
                          top: 0,
                          left: 0,
                          right: 0,
                          bottom: 0,
                          child: ClipRRect(
                            borderRadius:
                                BorderRadius.all(Radius.circular(4.px)),
                            child: ImageNetworkWidget(url),
                          ),
                        ),
                        ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(4.px)),
                          child: Container(
                            width: 64.px,
                            height: 40.px,
                            color: MyColors.color00A198,
                            alignment: Alignment.center,
                            child: Text(
                              '共创',
                              style: TextStyle(
                                  fontSize: 24.px, color: MyColors.white),
                            ),
                          ),
                        ),
                        if (list![index].hasVideo)
                          Positioned(
                              left: 4.px,
                              bottom: 4.px,
                              child: BaseImage(
                                image: 'icon_gcvideo',
                                width: 40.px,
                                height: 40.px,
                              ))
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 24.px,
                  ),
                  Expanded(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        caption,
                        style: TextStyle(
                            fontSize: 30.px, color: MyColors.color333333),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      if (msg != null)
                        Text(
                          msg,
                          style: TextStyle(
                              fontSize: 26.px, color: MyColors.color999999),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      tagWidget(list![index]),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                            onTap: () {
                              delCommon(index);
                            },
                            child: Container(
                              //设置 child 居中
                              alignment: Alignment.center,
                              height: 50.px,
                              width: 130.px,
                              //边框设置
                              decoration: BoxDecoration(
                                //背景
                                color: Colors.white,
                                //设置四周圆角 角度
                                borderRadius:
                                    BorderRadius.all(Radius.circular(4.px)),
                                //设置四周边框
                                border: Border.all(
                                    width: 1, color: MyColors.color979797),
                              ),
                              child: Text(
                                "删除",
                                style: TextStyle(
                                    fontSize: 26.px,
                                    color: MyColors.color666666),
                              ),
                            ),
                          ),
                          SizedBox(
                            width: 16.px,
                          ),
                          GestureDetector(
                            onTap: () {
                              PagePushUtils.push(
                                  context,
                                  CreatTravelScreen(
                                    id: list![index].id,
                                    endCallBack: (img, caption, hasVideo) {
                                      list![index].logo = img;
                                      list![index].caption = caption;
                                      list![index].hasVideo = hasVideo;
                                      setState(() {});
                                    },
                                  ));
                            },
                            child: Container(
                              //设置 child 居中
                              alignment: Alignment.center,
                              height: 50.px,
                              width: 130.px,
                              //边框设置
                              decoration: BoxDecoration(
                                //背景
                                color: Colors.white,
                                //设置四周圆角 角度
                                borderRadius:
                                    BorderRadius.all(Radius.circular(4.px)),
                                //设置四周边框
                                border: Border.all(
                                    width: 1, color: MyColors.color979797),
                              ),
                              child: Text(
                                "编辑",
                                style: TextStyle(
                                    fontSize: 26.px,
                                    color: MyColors.color666666),
                              ),
                            ),
                          )
                        ],
                      )
                    ],
                  ))
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget tagWidget(ListElement element) {
    if (element.tag == null || element.tag!.isEmpty) {
      return SizedBox();
    } else {
      return ClipRRect(
        borderRadius: const BorderRadius.all(Radius.zero),
        child: SizedBox(
          width: double.infinity,
          height: 46.px,
          child: Wrap(
            alignment: WrapAlignment.start,
            runAlignment: WrapAlignment.center,
            spacing: 11.px,
            runSpacing: 11.px,
            children: [
              for (int i = 0; i < element.tag!.length; i++)
                ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(6.px)),
                  child: Container( 
                    color: MyColors.color344,
                    child: Padding(
                        padding: EdgeInsets.all(8.px),
                        child: Text(
                          overflow: TextOverflow.visible,
                          element.tag![i],
                          style: TextStyle(
                              fontSize: 20.px, color: MyColors.colorEE7219),
                        )),
                  ),
                )
            ],
          ),
        ),
      );
    }
  }

  void getList() {
    Map<String, dynamic> params = Map();
    params['page'] = page;
    JetourHttp().get(JetourRouter.GuideMyGuide, params: params).then((value) {
      list ??= [];
      UserGuideListModel data = UserGuideListModel.fromJson(value);
      if (page == 1) {
        list!.clear();
      }
      list!.addAll(data.list);
      setState(() {});
      _controller.refreshEnd();
    });
  }

  void delCommon(int itemIndex) {
    showMyDialog(context, '是否删除', "是", "否", (index) {
      if (index == 0) {
        Map<String, dynamic> params = Map();
        params['id'] = list![itemIndex].id;
        JetourHttp().post(JetourRouter.GuideDelete, data: params).then((value) {
          list!.removeAt(itemIndex);
          setState(() {});
          if (list!.isEmpty) {
            getList();
          }
        });
      }
    });
  }
}
